local skel = fk.CreateSkill {
  name = "emo__emo",
}

--- D指导写的，将字符串乱码，可惜qml里字体识别不了乱码中文
local function randomSplitAndShuffle(s)
  local len = #s
  if len <= 1 then return s end  -- 短字符串直接返回

  -- 1. 随机切分：确定切割点（索引位置）
  local cutPoints = {0}  -- 起始位置
  for i = 1, len - 1 do
      if math.random() < 0.5 then  -- 概率切割（可调整）
          table.insert(cutPoints, i)
      end
  end
  table.insert(cutPoints, len)    -- 结束位置

  -- 2. 收集切割片段
  local segments = {}
  for i = 1, #cutPoints - 1 do
      local start = cutPoints[i] + 1
      local finish = cutPoints[i + 1]
      table.insert(segments, s:sub(start, finish))
  end

  -- 3. 随机打乱片段顺序（Fisher-Yates 洗牌）
  for i = #segments, 2, -1 do
      local j = math.random(1, i)
      segments[i], segments[j] = segments[j], segments[i]
  end

  -- 4. 重组字符串
  return table.concat(segments)
end

local function handleString(s)
    -- 替换所有成对的<...>
    s = s:gsub("%b<>", "")
    -- 删除未闭合的<
    s = s:gsub("<[^>]*$", "")
    return s
end

local markName = "@[emo]emo__emo"

skel:addEffect("active", {
  anim_type = "drawcard",
  mute = true,
  card_num = 0,
  target_num = 0,
  card_filter = Util.FalseFunc,
  prompt = "#emo__emo-prompt",
  times = function (self, player)
    return 1 - player:usedEffectTimes(self.name, Player.HistoryPhase)
  end,
  can_use = function(self, player)
    return player:usedEffectTimes(self.name, Player.HistoryPhase) < 1
  end,
  on_use = function(self, room, effect)
    local player = effect.from
    room:notifySkillInvoked(player, self.name, "offensive")
    player:broadcastSkillInvoke(self.name, 1)
    local generalPile = room.general_pile
    if #generalPile == 0 then return false end
    local name = room:askToChooseGeneral(player, {
      n = 1, generals = table.random(generalPile, 8), no_convert = true, extra_data = {skill_name = skel.name}
    })
    if type(name) == "table" then name = name[1] end
    table.removeOne(room.general_pile, name)
    local general = Fk.generals[name]

    room:sendLog{ type = "#EatGeneral", from = player.id, arg = general.name, toast = true }
    if general.package and general.package.extensionName then
      room:broadcastPlaySound("./packages/".. general.package.extensionName .."/audio/death/"..general.name)
    end
    -- 可惜加个炫酷死亡动画，但是我不会
    room:delay(500)

    local mark = player:getMark(markName)
    if mark == 0 then mark = {damage = 0, num = 0, text = ""} end

    local skill_list = general:getSkillNameList(true)
    if #skill_list > 0 then
      for _, skill in ipairs(skill_list) do
        local desc = handleString(Fk:translate(":"..skill, "zh_CN"))
        -- 这里应该处理一下，去掉font代码，还有翻译href注释
        mark.text = mark.text.. desc -- randomSplitAndShuffle(desc)
      end
    end

    -- 计算完整100的倍数数量
    local draw_num = math.floor(#mark.text / 300)
    mark.text = mark.text:sub(draw_num * 300 + 1)
    mark.num = (#mark.text / 3) % 100

    room:setPlayerMark(player, markName, mark)
    if draw_num > 0 then
      player:drawCards(draw_num, self.name)
      if player.dead then return end
    end

    local hp, maxHp, shield = general.hp, general.maxHp, general.shield
    if hp <= 0 and maxHp <= 0 and shield <= 0 then return end
    local prompt = shield == 0 and ("#emo__emo-eat:::"..hp..":"..maxHp)
    or ("#emo__emo-eat-shield:::"..hp..":"..maxHp..":"..shield)
    if not room:askToSkillInvoke(player, {skill_name = skel.name, prompt = prompt}) then return end

    mark.damage = mark.damage + 1
    room:setPlayerMark(player, markName, mark)

    room:changeMaxHp(player, maxHp)
    if not player.dead and player:isWounded() then
      room:recover({ who = player,  num = hp, skillName = self.name })
    end
    room:changeShield(player, shield)
  end,
})

Fk:addQmlMark{
  name = "emo",
  qml_path = "packages/moepack/qml/EmoEmoBox",
  how_to_show = function(_, value)
    if type(value) == "table" then
      local num = value.num
      if not num then return " " end
      local rest, n = num % 25, num // 25
      local text = ""
      for _ = 1, n do
        text = text.. "■"
      end
      if rest > 0 then
        local list = {"▏", "▎", "▍", "▌", "▋", "▊", "▉"}
        local len = #list
        local index = math.ceil(rest / 25 * len)
        rest = list[index] or list[len + index] or list[index - len] or ""
        text = text .. rest
      end
      return text
    end
    return " "
  end,
}

skel:addEffect(fk.DamageInflicted, {
  mute = true,
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(skel.name) and target == player and player:usedEffectTimes(self.name, Player.HistoryTurn) == 0 then
      local mark = player:getMark(markName)
      if type(mark) == "table" then
        return mark.damage > 0
      end
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:notifySkillInvoked(player, skel.name, "negative")
    player:broadcastSkillInvoke(skel.name, 2)
    data:changeDamage(player:getMark(markName).damage)
  end,
})

Fk:loadTranslationTable{
  ["emo__emo"] = "饿魔",
  [":emo__emo"] = "出牌阶段限一次，你可以从八张武将牌中选择一张，吞吃其技能，每有100字你摸一张牌，然后你还可吞吃其体力牌，获得其体力上限、体力值与护甲值，若如此做，你每回合首次受到伤害+1。",

  [markName] = "饿魔",
  ["#EatGeneral"] = "%arg 被 %from 吃掉了！",
  ["#emo__emo-prompt"] = "饿魔:你可以吃掉一个武将!",
  ["#emo__emo-eat"] = "饿魔：你可以吃掉其体力牌，获得%arg点体力和%arg2点体力上限，从此受伤害+1",
  ["#emo__emo-eat-shield"] = "饿魔：你可以吃掉其体力牌，获得%arg点体力、%arg2点体力上限、%arg3点护甲，从此受伤害+1",

  ["$emo__emo1"] = "我吃！我吃！我吃吃吃！",
  ["$emo__emo2"] = "尔等，竟如此歹毒！",
}

return skel
